import moment from 'moment';
import { PLoading, TRAlert } from '@/components';
import { isTRNumber } from '@/utils/attribute';
import { downloadHandle } from '#/utils/utils';
import { universalInterfaceExport } from '../services';

const LATITUDE_ENUM = {
  LATITUDE_MONTH: 'month',
  LATITUDE_DAY: 'day',
  LATITUDE_CONTINUITY: '96',
  LATITUDE_STACK: 'stack96',
  LATITUDE_HOURSTACK: 'stack24',
  LATITUDE_HOURCONTINUITY: '24',
};

const LATITUDE_TYPE = {
  [LATITUDE_ENUM.LATITUDE_MONTH]: '月',
  [LATITUDE_ENUM.LATITUDE_DAY]: '日',
  [LATITUDE_ENUM.LATITUDE_HOURCONTINUITY]: '24小时连续',
  [LATITUDE_ENUM.LATITUDE_HOURSTACK]: '24小时叠加',
  [LATITUDE_ENUM.LATITUDE_CONTINUITY]: '96点连续',
  [LATITUDE_ENUM.LATITUDE_STACK]: '96点叠加',
};

export const useExport = async (dataSource, obj) => {
  PLoading.show('正在导出...');
  const {
    latitude,
    provinceName,
    startDate,
    endDate,
    radixType,
    counterpartyTitle,
    columns,
    settlementUnitLists,
    type = 'main',
  } = obj;
  let columns_Arr = [];
  let dataSource_Arr = {};
  let dataSourceObj = [];
  columns.map((item) => {
    let s = item.width ? '' : item?.code;
    let name = s ? '' : typeof item.name === 'string' ? item.name : '类别';
    name = item.code === 'category' ? '类别' : name;
    if (!name) {
      const isDel = moment(s).format('HH:mm') === '00:00';
      if (latitude === LATITUDE_ENUM.LATITUDE_DAY) {
        name = moment(s).format('MM月DD日');
      } else if (
        latitude === LATITUDE_ENUM.LATITUDE_HOURSTACK ||
        latitude === LATITUDE_ENUM.LATITUDE_STACK
      ) {
        name = isDel ? '24:00' : moment(s).format('HH:mm');
      } else if (
        latitude === LATITUDE_ENUM.LATITUDE_HOURCONTINUITY ||
        latitude === LATITUDE_ENUM.LATITUDE_CONTINUITY
      ) {
        let _name = moment(s).format('MM月DD日') + '24:00';
        name = isDel ? _name : moment(s).format('MM月DD日 HH:mm');
      } else if (latitude === LATITUDE_ENUM.LATITUDE_MONTH) {
        name = `${item.name}月`;
      }
    }
    columns_Arr.push(name);
    dataSourceObj.push(item.code);
  });
  dataSource.map((item, index) => {
    dataSource_Arr[`${index}/${item.id}`] = [];
    dataSourceObj.map((k) => {
      let value =
        k === 'category' && typeof item[k] !== 'string'
          ? settlementUnitLists.filter((v) => v.stationId === item.id)[0]?.stationName
          : item[k] === null
          ? '-'
          : item[k];
      let _value = isTRNumber(value) ? String(value.toFixed(3)) : value;
      dataSource_Arr[`${index}/${item.id}`].push(_value);
    });
  });
  let result = [];
  Object.keys(dataSource_Arr).map((item) => {
    result.push(dataSource_Arr[item]);
  });
  let settlementUnitList_text = [
    ...new Set(
      dataSource
        .map((item) => {
          if (item?.stationName && typeof item?.stationName === 'string') return item.stationName;
        })
        .filter((item) => item),
    ),
  ].join(';');
  // settlementUnitLists
  //   .map(item => item?.stationName || item.name)
  //   .join(';');
  let params = {
    name: provinceName,
    data: [
      [
        '时间范围',
        `${moment(startDate).format('YYYY-MM-DD')}至${moment(endDate).format('YYYY-MM-DD')}`,
      ],
      ['对手方', `${counterpartyTitle}`],
      ['结算单元', `${settlementUnitList_text}`],
      ['基数归属', radixType === '1' ? '剩余仓位中含基数' : '合约中含基数'],
      ['导出维度', `${LATITUDE_TYPE[latitude]}`],
      ['数据来源页面', `仓位管理${type === 'main' ? '主' : '子'}页面`],
      [],
      columns_Arr,
      ...result,
    ],
  };

  let data = await universalInterfaceExport({
    exportType: 'positionManagement',
    jsonParam: params,
  });
  if (data && data?.data && data.data instanceof Blob) {
    PLoading.dismiss();
    const realFileName = data.response.headers.get('content-disposition').split('filename=')[1];
    downloadHandle(data.data, decodeURI(realFileName));
  } else {
    PLoading.dismiss();
    TRAlert.error('导出失败');
  }
};
